package alibaba.select.order;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainService extends AccessibilityService {
    private static final String TAG = "MainService";
    private static boolean hasClickedCorner = false;
    private static boolean hasClickedPayment = false;
    private static boolean hasSelectedOrders = false; // 是否已选择订单
    private static boolean taskCompleted = false; // 任务完成标志
    private static int orderSelectCount = 1; // 默认选择1个订单
    private static final String PAYMENT_BUTTON_ID = "com.alibaba.wireless:id/btn_payment";
    private static final String ORDER_ITEM_ID = "com.alibaba.wireless:id/cyber_item_container";
    
    // 用于存储已处理过的订单的唯一标识符
    private Set<String> processedOrderIds = new HashSet<>();

    /**
     * 重置点击状态
     */
    public static void resetClickState() {
        hasClickedCorner = false;
        hasClickedPayment = false;
        hasSelectedOrders = false;
        taskCompleted = false;
        Log.d(TAG, "重置所有点击状态");
    }
    
    /**
     * 设置要选中的订单数量
     * @param count 订单数量
     */
    public static void setOrderSelectCount(int count) {
        if (count > 0) {
            orderSelectCount = count;
            Log.d(TAG, "设置选中订单数量: " + count);
        } else {
            orderSelectCount = 1;
            Log.d(TAG, "无效的订单数量，设置为默认值1");
        }
    }
    
    @Override
    public void onInterrupt() {}

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        // 如果任务已完成，不执行任何操作
        if (taskCompleted) {
            return;
        }

        if (event != null && !event.getText().isEmpty() && event.getText().get(0).equals("推荐") ) {
            // 如果已经点击过，不再重复点击
            if (hasClickedCorner) {
                return;
            }

            AccessibilityNodeInfo node = event.getSource();
            Log.d(TAG, "node: " + node);
            findRecommendNodeRecursively( node);
            if (node != null) node.recycle();
        }

        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode != null) {
            try {
                // 如果已经点击过右下角，查找并点击代付款按钮
                if (hasClickedCorner) {
                    // 先点击代付款按钮
                    findAndClickPaymentButton(rootNode);
                    
                    // 如果已经点击了代付款按钮但还未选择订单，查找并选择订单
                    if (hasClickedPayment && !hasSelectedOrders) {
                        findAndSelectOrders(rootNode);
                    }
                }
                
                // 如果已经选择了订单但任务未完成，点击付款按钮
                if (hasSelectedOrders && !taskCompleted) {
                    clickPayAllButton(rootNode);
                }
            } finally {
                rootNode.recycle();
            }
        }
    }

    /**
     * 查找并点击代付款按钮
     */
    private void findAndClickPaymentButton(AccessibilityNodeInfo rootNode) {
        // 如果已经点击过代付款按钮，不再重复点击
        if (hasClickedPayment) {
            Log.d(TAG, "已经点击过代付款按钮，不再重复点击");
            return;
        }
        
        // 查找指定ID的节点
        AccessibilityNodeInfo paymentButton = findNodeById(rootNode, PAYMENT_BUTTON_ID);
        
        if (paymentButton != null) {
            try {
                Log.d(TAG, "找到代付款按钮，准备点击");
                // 使用click()方法点击节点
                paymentButton.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                // 设置已点击状态，避免重复点击
                hasClickedPayment = true;
                delay();
                Log.d(TAG, "已点击代付款按钮，并设置状态为已点击");
            } finally {
                paymentButton.recycle();
            }
        }
    }
    
    /**
     * 查找并选中指定数量的订单
     */
    private void findAndSelectOrders(AccessibilityNodeInfo rootNode) {
        if (rootNode == null) {
            Log.d(TAG, "根节点为空，无法选择订单");
            return;
        }
        
        // 清空已处理订单集合，开始新的选择过程
        processedOrderIds.clear();
        
        // 已选择的订单数量
        int selectedCount = 0;
        // 是否需要继续滚动查找订单
        boolean needContinue = true;
        // 记录滚动次数，防止无限滚动
        int scrollCount = 0;
        // 最大滚动次数限制
        final int MAX_SCROLL_COUNT = 100;
        // 连续没有新订单的次数
        int noNewOrdersCount = 0;
        // 最大连续没有新订单的次数限制
        final int MAX_NO_NEW_ORDERS_COUNT = 3;
        
        // 循环滚动查找订单，直到选择足够数量的订单或者无法继续滚动
        while (needContinue && selectedCount < orderSelectCount && scrollCount < MAX_SCROLL_COUNT && noNewOrdersCount < MAX_NO_NEW_ORDERS_COUNT) {
            // 查找当前可见的订单并选择
            int newlySelected = selectVisibleOrders(rootNode, selectedCount);
            selectedCount += newlySelected;
            
            // 如果本次没有选择到新订单，增加计数器
            if (newlySelected == 0) {
                noNewOrdersCount++;
                Log.d(TAG, "本次滚动未选择到新订单，连续 " + noNewOrdersCount + " 次未选择到新订单");
            } else {
                // 如果选择到了新订单，重置计数器
                noNewOrdersCount = 0;
            }
            
            // 如果已经选择了足够数量的订单，退出循环
            if (selectedCount >= orderSelectCount) {
                break;
            }
            
            // 查找可滚动的列表容器
            AccessibilityNodeInfo recyclerView = findNodeById(rootNode, "com.alibaba.wireless:id/cyber_recycler_view");
            
            // 检查是否找到可滚动容器并且可以向下滚动
            if (recyclerView != null) {
                try {
                    boolean canScrollForward = false;
                    
                    // 检查容器是否支持向下滚动操作
                    for (AccessibilityNodeInfo.AccessibilityAction action : recyclerView.getActionList()) {
                        if (action.getId() == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) {
                            canScrollForward = true;
                            break;
                        }
                    }
                    
                    if (canScrollForward) {
                        Log.d(TAG, "执行向下滚动操作，当前已选择 " + selectedCount + " 个订单");
                        // 执行向下滚动操作
                        boolean scrollSuccess = recyclerView.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                        if (scrollSuccess) {
                            scrollCount++;
                            // 滚动后等待内容加载
                            delay();
                            // 滚动后额外等待，确保内容完全加载
                            delay();
                        } else {
                            Log.d(TAG, "滚动操作失败，停止查找更多订单");
                            needContinue = false;
                        }
                    } else {
                        Log.d(TAG, "列表已到底部，无法继续滚动");
                        needContinue = false;
                    }
                } finally {
                    recyclerView.recycle();
                }
            } else {
                Log.d(TAG, "未找到可滚动的列表容器");
                needContinue = false;
            }
        }
        
        if (selectedCount > 0) {
            // 设置已选择订单标志
            hasSelectedOrders = true;
            Log.d(TAG, "订单选择完成，共选择了 " + selectedCount + " 个订单，准备点击付款按钮");
        } else {
            Log.d(TAG, "未能选择任何订单");
        }
    }
    
    /**
     * 选择当前可见的待付款订单
     * @param rootNode 根节点
     * @param alreadySelectedCount 已经选择的订单数量
     * @return 本次选择的订单数量
     */
    private int selectVisibleOrders(AccessibilityNodeInfo rootNode, int alreadySelectedCount) {
        // 查找所有列表项目
        List<AccessibilityNodeInfo> orderItems = rootNode.findAccessibilityNodeInfosByViewId(ORDER_ITEM_ID);
        
        if (orderItems == null || orderItems.isEmpty()) {
            Log.d(TAG, "当前页面未找到订单项目");
            return 0;
        }
        
        Log.d(TAG, "找到 " + orderItems.size() + " 个项目，准备筛选代付款订单");
        
        // 创建一个新列表来存储包含"代付款"文本的订单项
        List<AccessibilityNodeInfo> paymentOrderItems = new ArrayList<>();
        
        // 筛选包含"代付款"文本的订单项，并且跳过已处理的订单
        for (AccessibilityNodeInfo orderItem : orderItems) {
            if (hasPaymentTextView(orderItem)) {
                // 获取订单的唯一标识符
                String orderId = getOrderIdentifier(orderItem);
                
                // 如果这个订单已经处理过，跳过它
                if (processedOrderIds.contains(orderId)) {
                    Log.d(TAG, "跳过已处理过的订单: " + orderId);
                    continue;
                }
                
                // 添加到筛选后的列表中
                paymentOrderItems.add(AccessibilityNodeInfo.obtain(orderItem));
                
                // 将订单ID添加到已处理集合中
                processedOrderIds.add(orderId);
            }
        }
        
        Log.d(TAG, "筛选后找到 " + paymentOrderItems.size() + " 个新的代付款订单");
        
        if (paymentOrderItems.isEmpty()) {
            return 0;
        }
        
        // 计算本次需要选择的订单数量
        int remainingToSelect = orderSelectCount - alreadySelectedCount;
        int selectCount = Math.min(remainingToSelect, paymentOrderItems.size());
        
        Log.d(TAG, "本次将选择 " + selectCount + " 个订单");
        
        int successfullySelected = 0;
        
        // 选择指定数量的订单
        for (int i = 0; i < selectCount; i++) {
            AccessibilityNodeInfo orderItem = paymentOrderItems.get(i);
            try {
                // 在订单项目中查找第3个FrameLayout节点
                AccessibilityNodeInfo frameLayout = findNthNodeByClassName(orderItem, "android.widget.FrameLayout", 3);
                
                if (frameLayout != null && orderItem.getChildCount() >= 35) {
                    try {
                        Log.d(TAG, "找到代付款订单 #" + (alreadySelectedCount + successfullySelected + 1) + " 的FrameLayout节点，准备点击");
                        frameLayout.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        Log.d(TAG, "已点击代付款订单 #" + (alreadySelectedCount + successfullySelected + 1));
                        successfullySelected++;
                        delay();
                    } finally {
                        frameLayout.recycle();
                    }
                }
            } finally {
                orderItem.recycle();
            }
        }
        
        // 回收筛选后的列表中剩余的节点
        for (int i = selectCount; i < paymentOrderItems.size(); i++) {
            paymentOrderItems.get(i).recycle();
        }
        
        Log.d(TAG, "本次成功选择了 " + successfullySelected + " 个订单");
        return successfullySelected;
    }
    
    /**
     * 获取订单的唯一标识符
     * 尝试从订单项目中提取可以唯一标识该订单的信息
     * @param orderItem 订单项目节点
     * @return 订单的唯一标识符
     */
    private String getOrderIdentifier(AccessibilityNodeInfo orderItem) {
        if (orderItem == null) {
            return "unknown_" + System.currentTimeMillis();
        }
        
        StringBuilder identifier = new StringBuilder();
        int j = 0;
        // 收集所有文本内容，特别关注可能包含订单号、价格等的文本
        for (int i = 0; i<orderItem.getChildCount();i++) {
            AccessibilityNodeInfo textNode = orderItem.getChild(i);
            CharSequence text = textNode.getText();
            if (text != null && text.length() > 0) {
                identifier.append(text.toString()).append("_");
                if (++j > 5) break;
            }
            textNode.recycle();
        }

        // 如果没有找到足够的文本信息，尝试使用订单项目的内容描述
        if (identifier.length() < 10) {
            CharSequence contentDesc = orderItem.getContentDescription();
            if (contentDesc != null && contentDesc.length() > 0) {
                identifier.append("desc_").append(contentDesc);
            }
        }
        
        // 如果仍然没有足够的信息，使用订单项目的子节点数量和类名作为辅助标识
        if (identifier.length() < 10) {
            identifier.append("struct_")
                    .append(orderItem.getChildCount()).append("_")
                    .append(orderItem.getClassName()).append("_")
                    .append(System.currentTimeMillis() % 10000); // 添加时间戳的一部分，以防万一
        }
        
        return identifier.toString();
    }

    /** 延迟 */
    private void delay() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Log.e(TAG, "线程睡眠被中断", e);
        }
    }

    /**
     * 点击"付款"按钮
     */
    private void clickPayAllButton(AccessibilityNodeInfo rootNode) {
        if (rootNode == null) {
            Log.d(TAG, "根节点为空，无法点击付款按钮");
            return;
        }
        
        // 查找付款按钮
        List<AccessibilityNodeInfo> payAllButtons = rootNode.findAccessibilityNodeInfosByViewId("com.alibaba.wireless:id/tv_pay_all");

        if (!payAllButtons.isEmpty()) {
            AccessibilityNodeInfo payAllButton = payAllButtons.get(0);
            if (payAllButton.isClickable()) {
                payAllButton.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                Log.d(TAG, "已点击付款按钮");
                
                // 设置任务完成标志，防止循环执行
                taskCompleted = true;
                Log.d(TAG, "任务已完成，不再处理后续事件");
            } else {
                Log.d(TAG, "付款按钮不可点击");
            }
            payAllButton.recycle();
        } else {
            Log.d(TAG, "未找到付款按钮");
        }
    }
    
    /**
     * 检查节点是否包含className为"android.widget.TextView"且text为"代付款"的子节点
     */
    private boolean hasPaymentTextView(AccessibilityNodeInfo node) {
        if (node == null) return false;
        
        // 检查当前节点是否是TextView且文字为"待付款"
        if ("android.widget.TextView".equals(node.getClassName()) && 
            node.getText() != null && 
            "待付款".equals(node.getText().toString())) {
            return true;
        }
        
        // 递归检查所有子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            if (child != null) {
                try {
                    if (hasPaymentTextView(child)) {
                        return true;
                    }
                } finally {
                    child.recycle();
                }
            }
        }
        
        return false;
    }
    
    /**
     * 通过ID查找节点
     */
    private AccessibilityNodeInfo findNodeById(AccessibilityNodeInfo rootNode, String viewId) {
        if (rootNode == null) {
            return null;
        }
        
        // 直接使用findAccessibilityNodeInfosByViewId查找指定ID的节点
        List<AccessibilityNodeInfo> nodes = rootNode.findAccessibilityNodeInfosByViewId(viewId);
        if (nodes != null && !nodes.isEmpty()) {
            return nodes.get(0);
        }
        
        return null;
    }

    /**
     * 查找第N个指定类名的子节点
     * @param parent 父节点
     * @param className 要查找的类名
     * @param n 要查找的第几个节点（从1开始）
     * @return 找到的节点，如果未找到则返回null
     */
    private AccessibilityNodeInfo findNthNodeByClassName(AccessibilityNodeInfo parent, String className, int n) {
        if (parent == null || className == null || n <= 0) return null;
        
        // 创建一个计数器来跟踪找到的匹配节点数量
        int[] counter = {0};
        
        // 创建一个容器来存储结果
        AccessibilityNodeInfo[] result = {null};
        
        // 递归查找指定类名的第N个节点
        findNthNodeByClassNameRecursive(parent, className, n, counter, result);
        
        return result[0];
    }
    
    /**
     * 递归查找指定类名的第N个节点
     */
    private void findNthNodeByClassNameRecursive(AccessibilityNodeInfo node, String className, int n, int[] counter, AccessibilityNodeInfo[] result) {
        if (node == null || result[0] != null) return;
        
        // 检查当前节点是否匹配
        if (className.equals(node.getClassName())) {
            counter[0]++;
            if (counter[0] == n) {
                result[0] = AccessibilityNodeInfo.obtain(node);
                return;
            }
        }
        
        // 递归检查所有子节点
        for (int i = 0; i < node.getChildCount() && result[0] == null; i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            if (child != null) {
                try {
                    findNthNodeByClassNameRecursive(child, className, n, counter, result);
                } finally {
                    child.recycle();
                }
            }
        }
    }
    
    /**
     * 递归查找"推荐"文本节点
     */
    private void findRecommendNodeRecursively(AccessibilityNodeInfo node) {
        if (node == null) {
            return;
        }
        
        // 检查当前节点是否是TextView且文字为"推荐"
        if ("android.widget.TextView".equals(node.getClassName()) && 
            node.getText() != null && 
            "推荐".equals(node.getText().toString())) {
            
            // 检查父节点是否是ActionBar$Tab
            AccessibilityNodeInfo parent = node.getParent();
            if (parent != null) {
                try {
                    if ("android.app.ActionBar$Tab".equals(parent.getClassName())) {
                        Log.d(TAG, "找到推荐标签，准备点击屏幕右下角");

                        AccessibilityNodeInfo child = getRootInActiveWindow().getChild(8);
                        child.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        delay();
                        hasClickedCorner = true;
                        Log.d(TAG, "已设置点击状态，下一步将查找支付按钮");
                    }
                } finally {
                    parent.recycle();
                }
            }
        }
        
        // 递归检查子节点
        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo child = node.getChild(i);
            if (child != null) {
                try {
                    findRecommendNodeRecursively(child);
                } finally {
                    child.recycle();
                }
            }
        }
    }
}